package com.rocksea.app.http;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.mor.dataacquisition.net.BaseParser;
import com.mor.dataacquisition.net.RequestValue;
import com.mor.dataacquisition.net.parsedData.ResponseForLogin;
import com.rocksea.app.Account;
import com.rocksea.app.MyApplication;
import com.rocksea.app.utils.PerUtils;

import org.greenrobot.eventbus.EventBus;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import java.util.Date;
import java.util.LinkedHashMap;
import java.lang.Object;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import ICT.utils.RSACoder;

/**
 * Created by Mrw on 2017/8/5.
 *
 */
public class HttpUtil
{
    private static final String SECRET_KEY = "ROCKSEA0";

    public static void http(String methodName, LinkedHashMap<String,Object> mPropertys, OnRespond mOnRespond)
    {
        if (!isNetworkAvailable())
        {
            mOnRespond.onError(Config.INABLE_NET,"没有网络连接");
        }
        else
        {
            CommHttpTask task = new CommHttpTask(methodName,mPropertys,mOnRespond);
            task.execute();
        }
    }
    public static boolean isNetworkAvailable()
    {
        ConnectivityManager connectivity = (ConnectivityManager) MyApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            return ((info != null) && info.isConnected() && (info.getState() == NetworkInfo.State.CONNECTED));
        }
        return false;
    }
    public static String encyptDES(String encyptString){
        SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(),"DES");
        try {
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,keySpec);
            byte[] encrypteData = cipher.doFinal(encyptString.getBytes());
            return org.kobjects.base64.Base64.encode(encrypteData);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String upDateRandomCode()
    {
        RequestValue rValue1 = new RequestValue();
        rValue1.url = Config.BASE_URL+Config.getPublicKey;
        rValue1.parser = new BaseParser();
        Form form1 = new Form();
        form1.add("account", Account.getAccount());
        form1.add("mac", "RS");
        rValue1.form = form1;
        RequestValue rValue2 = new RequestValue();
        rValue2.url = Config.BASE_URL+Config.verifyAppUser;
        rValue2.parser = new BaseParser();
        Form form2 = new Form();
        form2.add("account", Account.getAccount());
        form2.add("mac", "RS");
        form2.add("pwdOrg", PerUtils.getString(Account.PASSWORD_KEY,""));
        form2.add("desPrivateKey", "12345678");
        rValue2.form = form2;

        String publicKey;
        ResponseForLogin respd = new ResponseForLogin();
        if(isNetworkAvailable())
        {
            publicKey = doRestLogin(rValue1);
            if(publicKey.length() == 128)
            {
                String pwd_jm = RSACoder.encnryptDes(rValue2.form.getFirstValue("pwdOrg"),rValue2.form.getFirstValue("desPrivateKey"));
                String deskey = RSACoder.encnryptRSA(rValue2.form.getFirstValue("desPrivateKey"), publicKey);
                rValue2.form.add("pwd", pwd_jm);
                rValue2.form.add("deskey", deskey);
                rValue2.form.removeFirst("pwdOrg");
                rValue2.form.removeFirst("desPrivateKey");
                respd.returnCode = doRestLogin(rValue2);
            }
            else
            {
                respd.returnCode = publicKey;
            }
            return respd.returnCode;
        }
        else
        {
            return "-90";
        }
    }

    public static String doRestLogin(RequestValue requestValue)
    {
        ClientResource client = new ClientResource(requestValue.url);
        Form form = requestValue.form;

        try {
            Representation entity = client.post(form.getWebRepresentation());
            return entity.getText();
        } catch (Exception var5) {
            var5.printStackTrace();
            return "-99";
        }
    }

    public static void postEvent(int level,String message)
    {
        UploadEvent uploadEvent = new UploadEvent();
        uploadEvent.message = message;
        uploadEvent.level = level;
        uploadEvent.time = PerUtils.dateToStr(new Date());
        EventBus.getDefault().post(uploadEvent);
    }

    public static class UploadEvent
    {
        public static final int NORMAL = 1;
        public static final int WARM = 2;
        public static final int ERROR = 3;

        public int level;
        public String message;
        public String time;
        public UploadEvent(){}
    }

    public static int doNetRest(RequestValue rValue,Form form)
    {
        ClientResource client = new ClientResource(rValue.url);
        try
        {
            Representation entity = client.post(form.getWebRepresentation());
            String text = entity.getText();
            return rValue.parser.parseObj(text).returnCode;
        }
        catch (Exception var6)
        {
            var6.printStackTrace();
        }
        return rValue.parser.parseObj("-99").returnCode;
    }

    public static boolean isImageAutoUpload()
    {
        return PerUtils.getBoolean(Account.IMAGE_AUTO_UPLOAD,false);
    }

    public static boolean isFileAutoUpload()
    {
        return PerUtils.getBoolean(Account.AUTO_UPLOAD,false);
    }



}
